package com.yjt.sousou.detail;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.yjt.sousou.Api;
import com.yjt.sousou.R;
import com.yjt.sousou.base.BaseActivity;
import com.yjt.sousou.base.BaseEntity;
import com.yjt.sousou.camera.preview.ImagePreviewActivity;
import com.yjt.sousou.create.PicRecycleAdapter;
import com.yjt.sousou.create.entity.Finish;
import com.yjt.sousou.create.entity.ImageItem;
import com.yjt.sousou.detail.entity.OrderDetail;
import com.yjt.sousou.detail.parts.SelectPartsActivity;
import com.yjt.sousou.http.DialogCallback;
import com.yjt.sousou.main.entity.RefreshData;
import com.yjt.sousou.user.LoginTag;
import com.yjt.sousou.utils.DensityUtil;
import com.yjt.sousou.utils.FixFileCallback;
import com.yjt.sousou.utils.GetTimeUtil;
import com.yjt.sousou.utils.HDFileUtil;
import com.yjt.sousou.utils.HDPreference;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.yjt.sousou.camera.preview.ImagePreviewActivity.CURRENT_POSITION;
import static com.yjt.sousou.camera.preview.ImagePreviewActivity.FROM;
import static com.yjt.sousou.camera.preview.ImagePreviewActivity.IMAGE_DATA;


/**
 * 作者：83734
 * 时间：2018/11/25
 * 描述：工单详情
 */
public class OrderDetailActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_dep_name)
    TextView mTvDepName;
    @BindView(R.id.tv_order_state)
    TextView mTvOrderState;
    @BindView(R.id.tv_order_num)
    TextView mTvOrderNum;
    @BindView(R.id.tv_report_time)
    TextView mTvReportTime;
    @BindView(R.id.tv_cause)
    TextView mTvCause;
    @BindView(R.id.tv_remark)
    TextView mTvRemark;
    @BindView(R.id.tv_repair)
    TextView mTvRepair;
    @BindView(R.id.tv_repair_time)
    TextView mTvRepairTime;
    @BindView(R.id.tv_receive_time)
    TextView mTvReceiveTime;
    @BindView(R.id.tv_finish_time)
    TextView mTvFinishTime;
    @BindView(R.id.tv_special_order)
    TextView mTvSpecialOrder;
    @BindView(R.id.tv_special_order_des)
    TextView mTvSpecialOrderDes;
    @BindView(R.id.tv_ev_time)
    TextView mTvEvTime;
    @BindView(R.id.tv_evaluate_name)
    TextView mTvEvaluateName;
    @BindView(R.id.tv_repair_des)
    TextView mTvRepairDes;
    @BindView(R.id.tv_ev_grade)
    TextView mTvGrade;
    @BindView(R.id.tv_ev_des)
    TextView mTvEvDes;
    @BindView(R.id.tv_parts_num)
    TextView mTvPartsNum;
    @BindView(R.id.tv_urgency)
    TextView mTvUrgency;
    @BindView(R.id.tv_appointment)
    TextView mTvAppointment;
    @BindView(R.id.tv_place)
    TextView mTvPlace;
    @BindView(R.id.ll_main)
    LinearLayout mLlMain;
    @BindView(R.id.rv_start_pic)
    RecyclerView mStartRv;
    @BindView(R.id.rv_finish_pic)
    RecyclerView mFinishRv;
    @BindView(R.id.ll_process)
    LinearLayout mLlProcess;
    @BindView(R.id.ll_evaluate)
    LinearLayout mLlEvaluate;
    @BindView(R.id.ll_receive_time)
    LinearLayout mLlReceiveTime;
    @BindView(R.id.ll_finish_time)
    LinearLayout mLlFinishTime;
    @BindView(R.id.ll_special_order)
    LinearLayout mLlSpecialOrder;
    @BindView(R.id.ll_button)
    LinearLayout mLlButton;
    @BindView(R.id.rl_parts)
    RelativeLayout mRlParts;
    @BindView(R.id.iv_play_audio)
    ImageView mIvPlayAudio;
    @BindView(R.id.iv_play_repair_audio)
    ImageView mIvPlayRepairAudio;

    private PicRecycleAdapter mStartPicAdapter;
    private PicRecycleAdapter mFinishPicAdapter;
    private ArrayList<ImageItem> mStartImgs = new ArrayList<>();
    private ArrayList<ImageItem> mFinishImgs = new ArrayList<>();
    private PopupWindow mPop;
    private String orderId= "";
    private OrderDetail.DataBean mDataBean;
    protected MediaPlayer mMediaPlayer;
    private String receiveTime = "";
    private static final int PROCESS_FINISH = 0X11;
    @Override
    protected Object setContentLayout() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        mTvTitle.setText(R.string.order_detail_main_title);
        mUserId =  HDPreference.getUserId(LoginTag.USER_ID.name());
        orderId = getIntent().getStringExtra("orderId");
        initRecycle();
        initData();
    }

    private void initRecycle() {
        LinearLayoutManager start = new LinearLayoutManager(this);
        start.setOrientation(LinearLayoutManager.HORIZONTAL);
        mStartRv.setLayoutManager(start);
        mStartPicAdapter= new PicRecycleAdapter(R.layout.item_select_pic,mStartImgs);
        mStartPicAdapter.setFrom(1);
        mStartRv.setAdapter(mStartPicAdapter);
        LinearLayoutManager finish = new LinearLayoutManager(this);
        finish.setOrientation(LinearLayoutManager.HORIZONTAL);
        mFinishRv.setLayoutManager(finish);
        mFinishPicAdapter= new PicRecycleAdapter(R.layout.item_select_pic,mFinishImgs);
        mFinishPicAdapter.setFrom(1);
        mFinishRv.setAdapter(mFinishPicAdapter);
        mStartPicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    ArrayList<ImageItem> images = new ArrayList<>(mStartImgs);
                    Intent intent = new Intent(getApplicationContext(), ImagePreviewActivity.class);
                    intent.putExtra(CURRENT_POSITION,position);
                    intent.putExtra(IMAGE_DATA,images);
                    intent.putExtra(FROM,1);
                    startActivity(intent);
            }
        });
        mFinishPicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    ArrayList<ImageItem> images = new ArrayList<>(mFinishImgs);
                    Intent intent = new Intent(getApplicationContext(),ImagePreviewActivity.class);
                    intent.putExtra(CURRENT_POSITION,position);
                    intent.putExtra(IMAGE_DATA,images);
                    intent.putExtra(FROM,1);
                    startActivity(intent);
            }
        });
    }

    private String getUrgency(String rlevel){
        String urgency = "";
        switch (rlevel){
            case "1":
                urgency = "紧急";
                mTvUrgency.setTextColor(ContextCompat.getColor(this,R.color.circle_integral_excellent));
                break;
            case "2":
                urgency = "一般";
                break;
            case "3":
                urgency = "正常";
                break;
        }
        return urgency;
    }

    private void initData() {
        OkGo.<OrderDetail>get(Api.get().getOrderDetail())
                .tag(this)
                .params("id",orderId)
                .params("user_id",mUserId)
                .execute(new DialogCallback<OrderDetail>(OrderDetail.class,this) {
                    @Override
                    public void onSuccess(Response<OrderDetail> response) {
                        OrderDetail body = response.body();
                        if(body.getReturncode().equals("0")){
                            mDataBean = body.getData().get(0);
                            mTvDepName.setText(mDataBean.getBaoxiu());
                            mTvOrderState.setText(getOrderStateStr(mDataBean.getWxzt()));
                            mTvOrderNum.setText(mDataBean.getOrderid());
                            mTvUrgency.setText(getUrgency(mDataBean.getRlevel()));

                            if(!TextUtils.isEmpty(mDataBean.getCreate_time())){
                                long createTime = Long.parseLong(mDataBean.getCreate_time());
                                mTvReportTime.setText(GetTimeUtil.getYMDHM(createTime*1000));
                            }
                            mTvAppointment.setText(mDataBean.getAppointment_time_name());
                            mTvPlace.setText(mDataBean.getQuyu());

                            setOrderSateShow(mDataBean.getWxzt());
                            setCause(1);
                            mTvRemark.setText(mDataBean.getBeizhu());
                            setCause(2);

                            mTvRepair.setText(mDataBean.getWeixiuyuan());
//                            mTvOrderType.setText(mDataBean.getRlevel_name());
                            mTvRepairTime.setText(mDataBean.getPg_time_name());
                            if(!TextUtils.isEmpty(mDataBean.getJiedan_time_name())){
                                mTvReceiveTime.setText(mDataBean.getJiedan_time_name());
                            }else {
                                mLlReceiveTime.setVisibility(View.GONE);
                            }
                            receiveTime = mDataBean.getJiedan_time_name();
                            if(!TextUtils.isEmpty(mDataBean.getEnd_time_name())){
                                mTvFinishTime.setText(mDataBean.getEnd_time_name());
                            }else {
                                mLlFinishTime.setVisibility(View.GONE);
                            }
                            if(!TextUtils.isEmpty(mDataBean.getCollection_name())){
                                mLlSpecialOrder.setVisibility(View.VISIBLE);
                                mTvSpecialOrder.setText(mDataBean.getCollection_name());
                                mTvSpecialOrderDes.setText(mDataBean.getCollection_note());
                            }else {
                                mLlSpecialOrder.setVisibility(View.GONE);
                            }

                            mTvEvTime.setText(mDataBean.getPj_time_name());
                            mTvEvaluateName.setText(mDataBean.getPj_name());

                            String partsNum = mDataBean.getPeijian_con()==null|(mDataBean.getPeijian_con()!=null&&mDataBean.getPeijian_con().size()==0)
                                    ?"0":String.valueOf(mDataBean.getPeijian_con().size());
                            if("0".equals(partsNum)){
                                mRlParts.setVisibility(View.GONE);
                            }else {
                                mRlParts.setVisibility(View.VISIBLE);
//                                mTvPartsNum.setText(partsNum);
                            }
                            mTvGrade.setText(mDataBean.getYouping_name());
                            mTvEvDes.setText(mDataBean.getPingjia_beizhu());

                            setPic();
                            mLlButton.removeAllViews();
                            for (OrderDetail.DataBean.ButtonData b : mDataBean.getButton_arr()) {
                                setButton(b);
                            }
                            mStartPicAdapter.notifyDataSetChanged();
                            mFinishPicAdapter.notifyDataSetChanged();
                        }else {
                            showToast("获取失败："+body.getReturnmsg());
                        }
                    }
                });
    }

    //设置按钮
    private void setButton(OrderDetail.DataBean.ButtonData button) {
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(16);
        textView.setText(button.getWord());
        textView.setTag(button.getButton_id());
        textView.setBackgroundResource(R.drawable.rectangle_blue);
        textView.setTextColor(ContextCompat.getColor(this,R.color.white));
        textView.setPadding(DensityUtil.dip2px(this,20),DensityUtil.dip2px(this,5),DensityUtil.dip2px(this,20)
        ,DensityUtil.dip2px(this,5));
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 setButtonClick((int) v.getTag(),v);
            }
        });
        mLlButton.addView(textView);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(DensityUtil.dip2px(this,5),0,DensityUtil.dip2px(this,5),0);
        params.weight=1;
        textView.setLayoutParams(params);
    }
    private void setButtonClick(int tag, View view) {
        Intent intent = null;
        switch (tag) {
            //接单
            case 1:
               receiveOrder();
                break;
            //派工
            case 2:
                intent = new Intent(this,DispatchingActivity.class);
                intent.putExtra("orderId",orderId);
                startActivity(intent);
                break;
            //维修工程
            case 3:
                intent = new Intent(this,ProcessActivity.class);
                intent.putExtra("orderId",orderId);
                intent.putExtra("receiveTime",receiveTime);
                intent.putExtra("repairState",mDataBean.getZhuangtai());
                intent.putExtra("weixiuyuan",mDataBean.getWeixiuyuan());
                intent.putExtra("weixiuyuanids",mDataBean.getWeixiuyuan_ids());
                intent.putParcelableArrayListExtra("faulttypes",mDataBean.getFaulttype_info());
                startActivityForResult(intent,PROCESS_FINISH);
                break;
            //退单
            case 4:
                backOrder();
                break;
            //删除
            case 5:
                showConfirmPop();
                makeWindowDark();
                break;
            //评价
            case 6:
                showEvaluatePop();
                makeWindowDark();
                break;
            //配件
            case 7:
                intent = new Intent(this, SelectPartsActivity.class);
                intent.putExtra("orderId",orderId);
                startActivityForResult(intent,PROCESS_FINISH);
                break;
                default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == PROCESS_FINISH && resultCode == RESULT_OK){
            initData();
        }
    }
    //确定删除
    private void showConfirmPop() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_confirm,null);
        TextView tv_in_work = view.findViewById(R.id.tv_ok);
        TextView tv_pop_title = view.findViewById(R.id.tv_pop_title);
        TextView tv_close = view.findViewById(R.id.tv_no);
        tv_pop_title.setText("确定删除");
        mPop = new PopupWindow(view, 4 * mScreenWidth / 5,ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.showAtLocation(mLlMain, Gravity.CENTER, 0, 0);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_in_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
                deleteOrder();
            }
        });
    }
    //根据state显示不同模块
    private void setOrderSateShow(String workState) {
           int state = Integer.parseInt(workState);
           if(state>1){
               mLlProcess.setVisibility(View.VISIBLE);
           }
           if(state>4&&!TextUtils.isEmpty(mDataBean.getPj_name())){
               mLlEvaluate.setVisibility(View.VISIBLE);
           }
    }
    private String getOrderStateStr(String state){
        String orderState = "";
        switch (state){
            case "1":
                orderState = "未派工";
                break;
            case "2":
                orderState = "维修中";
                break;
            case "3":
                orderState = "评价";
                break;
            case "4":
                orderState = "配件处理";
                break;
            case "5":
                orderState = "已完结";
                break;
        }
        return orderState;
    }
    private void setPic() {
        mStartImgs.clear();
        mFinishImgs.clear();
        for (OrderDetail.DataBean.FileBean file : mDataBean.getGz_file_jpg_arr()) {
            try {
                if (!TextUtils.isEmpty(file.getThumb_pic()))
                    mStartImgs.add(new ImageItem(new URL(file.getThumb_pic()),file.getFile_path(),false));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        for (OrderDetail.DataBean.FileBean file : mDataBean.getGz_file_mp4_arr()) {
            try {
                if (!TextUtils.isEmpty(file.getThumb_pic()))
                    mStartImgs.add(new ImageItem(new URL(file.getFile_path()),file.getFile_path(),true));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        for (OrderDetail.DataBean.FileBean file : mDataBean.getWc_file_jpg_arr()) {
            try {
                if (!TextUtils.isEmpty(file.getThumb_pic()))
                    mFinishImgs.add(new ImageItem(new URL(file.getThumb_pic()),file.getFile_path(),false));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        for (OrderDetail.DataBean.FileBean file : mDataBean.getWc_file_mp4_arr()) {
            try {
                if (!TextUtils.isEmpty(file.getThumb_pic()))
                    mFinishImgs.add(new ImageItem(new URL(file.getFile_path()),file.getFile_path(),true));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }

    protected void playAudio(Uri audioUri){
            if(mMediaPlayer == null){
                mMediaPlayer = MediaPlayer.create(this,audioUri);
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
//                        recycleMediaPlayer();
                    }
                });
            }
            if(mMediaPlayer.isPlaying()){
                mMediaPlayer.pause();
            }else {
                mMediaPlayer.start();
            }
    }
    //1 报修 2 维修
    private void setCause(final int type){
        final List<OrderDetail.DataBean.FileBean> fileBeans = type==1?mDataBean.getGz_file_mp3_arr():mDataBean.getWc_file_mp3_arr();
        if(fileBeans.size()>0){
            if(type == 1){
                mIvPlayAudio.setVisibility(View.VISIBLE);
                mIvPlayAudio.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AnimationDrawable animationDrawable = (AnimationDrawable) mIvPlayAudio.getDrawable();
                        animationDrawable.start();
                        download(fileBeans.get(0).getFile_path());
                    }
                });
            }else {
                mIvPlayRepairAudio.setVisibility(View.VISIBLE);
                mIvPlayRepairAudio.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AnimationDrawable animationDrawable = (AnimationDrawable) mIvPlayRepairAudio.getDrawable();
                        animationDrawable.start();
                        download(fileBeans.get(0).getFile_path());
                    }
                });
            }
        }
        if(type == 1){
            mTvCause.setText(mDataBean.getYuanyin());
        }else {
            mTvRepairDes.setText(mDataBean.getGongzuomiaoshu());
        }
    }
    private void download(String url){
        String fileDir = Utils.getApp().getExternalFilesDir("img") + File.separator + "JCamera";
        String fileName = "download_"+url.substring(url.lastIndexOf("/")+1);
        LogUtils.i(fileName);
        if(HDFileUtil.isFileExit(fileDir,fileName)){
            Uri uri = HDFileUtil.getFileUri(new File(fileDir,fileName),this);
            playAudio(uri);
        }else {
            OkGo.<File>get(url)
                    .tag(this)
                    .execute(new FixFileCallback(fileDir,fileName) {
                        @Override
                        public void onStart(Request<File, ? extends Request> request) {
                            super.onStart(request);
                            showToast("正在加载语音");
                        }
                        @Override
                        public void onSuccess(Response<File> response) {
                            showToast("加载完成");
                            Uri uri = HDFileUtil.getFileUri(response.body(),getApplicationContext());
                            playAudio(uri);
                        }
                        @Override
                        public void onError(Response<File> response) {
                            super.onError(response);
                            showToast("加载失败");
                        }
                    });
        }
    }

    @OnClick({R.id.iv_logs,R.id.rl_parts})
    void onClick(View v){
        Intent intent = null;
        switch (v.getId()){
            case R.id.iv_logs:
                intent = new Intent(this,OrderLogActivity.class);
                intent.putParcelableArrayListExtra("logs",mDataBean.getLog());
                startActivity(intent);
                break;
            case R.id.rl_parts:
                if(!"0".equals(mTvPartsNum.getText().toString())){
                    intent = new Intent(this,PartsListActivity.class);
                    intent.putParcelableArrayListExtra("parts",mDataBean.getPeijian_con());
                    startActivity(intent);
                }
                break;
        }
    }

    private int endState = 1;//结束状态
    private int evGrade = 1;//评价等级
    private void showEvaluatePop() {
        final List<TextView> sovles = new ArrayList<>();
        final List<TextView> evgrades = new ArrayList<>();
        View view = LayoutInflater.from(this).inflate(R.layout.pop_evaluate,null);
        TextView tv_pop_title = view.findViewById(R.id.tv_pop_title);
        final EditText tv_evaluate_content = view.findViewById(R.id.tv_evaluate_content);
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        TextView tv_solve = view.findViewById(R.id.tv_solve);
        TextView tv_no_solve = view.findViewById(R.id.tv_no_solve);
        final TextView tv_content = view.findViewById(R.id.tv_content);

        final TextView tv_ev_grade = view.findViewById(R.id.tv_ev_grade);
        final LinearLayout ll_ev_grade = view.findViewById(R.id.ll_ev_grade);
        final TextView tv_back = view.findViewById(R.id.tv_back);

        sovles.add(tv_solve);
        sovles.add(tv_no_solve);
        tv_solve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_content.setText("评价内容");
                tv_ev_grade.setVisibility(View.VISIBLE);
                ll_ev_grade.setVisibility(View.VISIBLE);
                tv_back.setVisibility(View.GONE);
                evGrade = 1;
                setState(sovles,0);
            }
        });
        tv_no_solve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_ev_grade.setVisibility(View.GONE);
                ll_ev_grade.setVisibility(View.GONE);
                tv_back.setVisibility(View.VISIBLE);
                tv_content.setText("驳回说明");
                evGrade = 0;
                setState(sovles,1);
            }
        });

        TextView tv_normal = view.findViewById(R.id.tv_normal);
        TextView tv_well = view.findViewById(R.id.tv_well);
        TextView tv_good = view.findViewById(R.id.tv_good);
        evgrades.add(tv_good);
        evgrades.add(tv_well);
        evgrades.add(tv_normal);
        tv_good.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                evGrade = 1;
                setState(evgrades,0);
            }
        });
        tv_normal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                evGrade = 3;
                setState(evgrades,2);
            }
        });
        tv_well.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                evGrade = 2;
                setState(evgrades,1);
            }
        });
        tv_pop_title.setText("评价");
        ImageView tv_close = view.findViewById(R.id.tv_close);

        mPop = new PopupWindow(view, 4 * mScreenWidth / 5,ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.showAtLocation(mLlMain, Gravity.CENTER, 0, 0);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = tv_evaluate_content.getText().toString();
                String evContent = endState==1?content:"";
                String baContent = endState==2?content:"";
                mPop.dismiss();
                evaluate(evContent,baContent);
            }
        });
    }

    private void evaluate(String evContent,String baContent) {
        OkGo.<BaseEntity>post(Api.get().getOrderEvaluate()).tag(this)
                .params("id",orderId)
                .params("opt_uid",mUserId)
                .params("end_state",endState)
                .params("youping",evGrade)
                .params("pingjia_beizhu",evContent)
                .params("bh_beizhu",baContent)
                .execute(new DialogCallback<BaseEntity>(BaseEntity.class,this) {
                    @Override
                    public void onSuccess(Response<BaseEntity> response) {
                        BaseEntity entity = response.body();
                        if(entity.getReturncode().equals("0")){
                            showToast("评价成功");
                            initData();
                        }else {
                            showToast("评价失败:"+entity.getReturnmsg());
                        }
                    }
                });
    }

    //接单
    private void receiveOrder() {
         OkGo.<Finish>post(Api.get().getOrderReceive())
                 .tag(this)
                 .params("user_id",mUserId)
                 .params("id",orderId)
                 .execute(new DialogCallback<Finish>(Finish.class,this) {
                     @Override
                     public void onSuccess(Response<Finish> response) {
                         Finish entity = response.body();
                         if(entity.getReturncode().equals("0")){
                             showToast("接单成功");
                             EventBus.getDefault().post(new RefreshData(0));
                             finish();
                         }else {
                             showToast("接单失败:"+entity.getReturnmsg());
                         }
                     }
                 });
    }
    //退单
    private void backOrder(){
        OkGo.<Finish>post(Api.get().getOrderReturn())
                .tag(this)
                .params("opt_uid",mUserId)
                .params("id",orderId)
                .execute(new DialogCallback<Finish>(Finish.class,this) {
                    @Override
                    public void onSuccess(Response<Finish> response) {
                        Finish entity = response.body();
                        if(entity.getReturncode().equals("0")){
                            showToast("退单成功");
                            EventBus.getDefault().post(new RefreshData(0));
                            finish();
                        }else {
                            showToast("退单失败:"+entity.getReturnmsg());
                        }
                    }
                });
    }
    //删除工单
    private void deleteOrder(){
        OkGo.<Finish>post(Api.get().getOrderDelete())
                .tag(this)
                .params("opt_uid",mUserId)
                .params("id",orderId)
                .execute(new DialogCallback<Finish>(Finish.class,this) {
                    @Override
                    public void onSuccess(Response<Finish> response) {
                        Finish entity = response.body();
                        if(entity.getReturncode().equals("0")){
                            showToast("删除成功");
                            EventBus.getDefault().post(new RefreshData(0));
                            finish();
                        }else {
                            showToast("删除失败:"+entity.getReturnmsg());
                        }
                    }
                });
    }
}
